package com.example.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.entity.ShouCang;
import com.example.backend.mapper.IShouCangMapper;
import com.example.backend.service.IShouCangService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class ShouCangService implements IShouCangService {
    @Resource
    private IShouCangMapper shouCangMapper;

    @Override
    public boolean addShouCang(ShouCang shouCang) {
        return shouCangMapper.insert(shouCang) > 0;
    }

    @Override
    public boolean deleteShouCang(Integer scid) {
        return shouCangMapper.deleteById(scid) > 0;
    }

    @Override
    public boolean updateShouCang(ShouCang shouCang) {
        return shouCangMapper.updateById(shouCang) > 0;
    }

    @Override
    public IPage<ShouCang> selectShouCang(ShouCang shouCang,Integer currentPage,Integer pageSize,String sortField,String sortOrder) {
        LambdaQueryWrapper<ShouCang> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(shouCang.getScid() != null, ShouCang::getScid, shouCang.getScid())
                .eq(shouCang.getYhid() != null, ShouCang::getYhid, shouCang.getYhid())
                .eq(shouCang.getSjid() != null, ShouCang::getSjid, shouCang.getSjid());

        if (sortField != null && !sortField.isEmpty() && sortOrder != null && !sortOrder.isEmpty()) {
            SFunction<ShouCang, ?> column = getColumnByField(sortField);
            if (column != null) {
                if ("asc".equalsIgnoreCase(sortOrder)) {
                    wrapper.orderByAsc(column);
                } else {
                    wrapper.orderByDesc(column);
                }
            }
        }
        Page<ShouCang> page = new Page<>(currentPage,pageSize);
        return shouCangMapper.selectPage(page,wrapper);
    }

    @Override
    public boolean findSc(Integer yhid, Integer sjid) {
        Integer count = shouCangMapper.findSc(yhid, sjid);
        if (count != null && count > 0) {
            return false; // 已有收藏记录，不插入
        }
        ShouCang sc = new ShouCang();
        sc.setYhid(yhid);
        sc.setSjid(sjid);
        int result = shouCangMapper.insert(sc);
        return result > 0; // 返回插入是否成功
    }

    private SFunction<ShouCang, ?> getColumnByField(String field) {
        return switch (field) {
            case "scid" -> ShouCang::getScid;
            case "yhid" -> ShouCang::getYhid;
            case "sjid" -> ShouCang::getSjid;
            default -> null;
        };
    }


}
